import { changePass } from '@/services/api';
import { Form, Input, message, Modal } from 'antd';
import md5 from 'js-md5';
import React, { useEffect } from 'react';

interface ChangePassModalProps {
  open: boolean;
  setOpen: (open: boolean) => void;
}

const ChangePassModal: React.FC<ChangePassModalProps> = (props) => {
  const [form] = Form.useForm();
  const { open, setOpen } = props;
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  useEffect(() => {
    form.resetFields();
  }, [open]);
  const handleCancel = () => {
    setOpen(false);
  };
  const handleOk = async () => {
    const values = await form.validateFields();
    setConfirmLoading(true);
    await changePass({
      old_password: md5(values.oldPass),
      new_password: md5(values.newPass),
    }).catch(() => {
      setConfirmLoading(false);
    });
    message.success('修改成功');
    setConfirmLoading(false);
    setOpen(false);
  };
  return (
    <Modal
      title="修改密码"
      open={open}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      onCancel={handleCancel}
      closeIcon={false}
      maskClosable={false}
    >
      <Form form={form} layout="vertical" size="small">
        <Form.Item
          name="oldPass"
          label="旧密码"
          rules={[{ required: true, message: '旧密码必填' }]}
        >
          <Input.Password placeholder="请输入旧密码" />
        </Form.Item>
        <Form.Item
          name="newPass"
          label="新密码"
          rules={[{ required: true, message: '新密码必填' }]}
        >
          <Input.Password placeholder="请输入新密码" />
        </Form.Item>
        <Form.Item
          name="confirmPass"
          label="确认新密码"
          rules={[
            { required: true, message: '确认新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPass') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次新密码输入不一致！'));
              },
            }),
          ]}
        >
          <Input.Password placeholder="确认新密码" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ChangePassModal;
